package org.com.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.pattern.PathPatternParser;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    private static final PathPatternParser PATH_PATTERN_PARSER = new PathPatternParser();

    private  SecurityConfig securityConfig;
    /**
     * 是否开启云服务
     */
    @Value(value = "${spring.cloud.nacos.discovery.enabled:true}")
    private Boolean cloudFlag;

    public TokenInterceptor(SecurityConfig securityConfig) {
        this.securityConfig = securityConfig;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("preHandle");
        //云环境下Token都有网关处理好了，这边直接可以从request头部获取
//        if (cloudFlag) {
//            UserContext.set(UserConstant.LOGIN_USER_NAME, request.getHeader(UserConstant.LOGIN_USER_NAME));
//            UserContext.set(UserConstant.LOGIN_USER, request.getHeader(UserConstant.LOGIN_USER));
//            UserContext.set(UserConstant.LANGUAGE_TYPE, request.getHeader(UserConstant.LANGUAGE_TYPE));
//            return true;
//        }

        return standAlone(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        UserContext.clean();
        System.out.println("afterCompletion");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }


    /**
     * 单机运行解析token
     *
     * @param request request
     * @param response response
     * @param handler handler
     * @return boolean
     */
    private boolean standAlone(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("standAlone");
        //options不拦截
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            return Boolean.TRUE;
        }

        //白名单筛选
//        List<String> ignoreUri = securityConfig.getIgnoreUri();
//        String matchUri = request.getRequestURI();
//        boolean flag = ignoreUri.stream().anyMatch(uri -> PATH_PATTERN_PARSER.parse(uri).matches(PathContainer.parsePath(matchUri)));
//        if (flag) {
//            return Boolean.TRUE;
//        }

        //token非空检查
//        String token = request.getHeader(securityConfig.getTokenHeader());
//        if (StringUtils.isEmpty(token)) {
//            String errorMsg = "Token不能为空";
//            log.error("【Token校验】Token验证失败：{}", errorMsg);
//            response.sendError(401, errorMsg);
//            return Boolean.FALSE;
//        }

        //校验Token
//        boolean result = TokenUtil.verify(token);
//        if (!result) {
//            String errorMsg = "非法Token";
//            log.error("【Token校验】Token验证失败：{}", errorMsg);
//            response.sendError(401, errorMsg);
//            return Boolean.FALSE;
//        }

        //解析token
//        LoginInfo userInfo = TokenUtil.getUserInfo(token);
//        UserContext.set(UserConstant.LOGIN_USER_NAME, userInfo.getUserName());
//        UserContext.set(UserConstant.LOGIN_USER, userInfo);
//        UserContext.set(UserConstant.LANGUAGE_TYPE, request.getHeader(UserConstant.LANGUAGE_TYPE));
        return Boolean.TRUE;
    }
}
